package util

import java.net.URL
import java.net.URLEncoder
import java.util.regex.Pattern
import java.util.regex.Matcher
import scala.io.BufferedSource

object LehdenUrlParser {

  def matchUrl(matcher: Matcher): Option[URL] = {
    if (matcher.matches) {
      val parts = matcher.group(1).split("\\?|&amp;")
      val params = parts.tail.map(_.split("=")).map(a => a(0) + "=" + URLEncoder.encode(a(1))).mkString("&")
      Some(new URL(parts.head + "?" + params))
    } else {
      None
    }
  }

  def parseUrlFromHtml(in: BufferedSource): Option[URL] = {
    try {
      val pattern = Pattern.compile(".+HREF=\"([^\"]+)\".+")
      in.getLines().foldLeft(None: Option[URL]) { (a, b) =>
        matchUrl(pattern.matcher(b)) match {
          case Some(url) => Some(url)
          case None => a
        }
      }
    } finally {
      in.close()
    }
  }
}
